<template>
  <el-dialog
    v-model="dialogVisible"
    title="设备二维码"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="qrcode-container">
      <!-- 二维码大小调整 -->
      <div class="size-control">
        <el-form :model="qrcodeConfig" label-width="80px">
          <el-form-item label="二维码大小">
            <div class="size-display">
              <span class="size-text">{{ qrcodeConfig.size }}px</span>
              <el-button size="small" @click="resetSize">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 二维码预览区域 -->
      <div class="qrcode-preview" :style="{ textAlign: 'center' }">
        <div v-if="loading" class="loading-container">
          <el-skeleton animated>
            <template #template>
              <div style="padding: 20px">
                <el-skeleton-item variant="image" style="width: 200px; height: 200px" />
                <div style="padding: 14px">
                  <el-skeleton-item variant="h3" style="width: 50%" />
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                      margin-top: 16px;
                    "
                  >
                    <el-skeleton-item variant="text" style="margin-right: 16px" />
                    <el-skeleton-item variant="text" style="width: 30%" />
                  </div>
                </div>
              </div>
            </template>
          </el-skeleton>
        </div>

        <div v-else-if="qrcodeData" class="qrcode-content">
          <div class="qrcode-card" :style="{ width: qrcodeConfig.size + 'px' }" ref="qrcodeCardRef">
            <div class="qrcode-header">
              <h3>{{ deviceInfo.deviceName || '设备二维码' }}</h3>
              <p class="device-id">{{ deviceInfo.deviceKey }}</p>
            </div>

            <div class="qrcode-image">
              <img
                :src="qrcodeData"
                :alt="deviceInfo.deviceName"
                :style="{
                  width: qrcodeConfig.size - 40 + 'px',
                  height: qrcodeConfig.size - 40 + 'px'
                }"
              />
            </div>

            <div class="qrcode-footer">
              <p class="device-type">设备类型: {{ getDeviceTypeName(deviceInfo.deviceType) }}</p>
            </div>

            <!-- 拖拽调整大小的手柄 -->
            <div class="resize-handle" @mousedown.stop="startResize"></div>
          </div>
        </div>

        <div v-else class="error-container">
          <el-empty description="二维码加载失败" />
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="handlePrint" :disabled="!qrcodeData">
          <Icon icon="ep:printer" class="mr-5px" /> 打印
        </el-button>
      </div>
    </template>

    <!-- 打印预览对话框 -->
    <el-dialog v-model="printPreviewVisible" title="打印预览" width="600px" append-to-body>
      <div class="print-preview">
        <div class="print-controls">
          <el-form :model="printConfig" label-width="100px" inline>
            <el-form-item label="打印大小">
              <el-select v-model="printConfig.size" style="width: 140px">
                <el-option label="小" value="small" />
                <el-option label="中" value="medium" />
                <el-option label="大" value="large" />
                <el-option label="当前大小" value="current" />
              </el-select>
            </el-form-item>
            <el-form-item label="打印数量">
              <el-input-number
                v-model="printConfig.count"
                :min="1"
                :max="10"
                style="width: 120px"
              />
            </el-form-item>
          </el-form>
          <div class="print-info">
            <p>当前二维码大小: {{ qrcodeConfig.size }}px</p>
            <p>打印尺寸: {{ getPrintItemWidth() }}px</p>
          </div>
        </div>

        <div class="print-content" ref="printContentRef">
          <div
            v-for="i in printConfig.count"
            :key="i"
            class="print-item"
            :class="printConfig.size"
            :style="{ width: getPrintItemWidth() + 'px' }"
          >
            <div class="qrcode-header">
              <h3>{{ deviceInfo.deviceName || '设备二维码' }}</h3>
              <p class="device-id">{{ deviceInfo.deviceKey }}</p>
            </div>

            <div class="qrcode-image">
              <img
                :src="qrcodeData"
                :alt="deviceInfo.deviceName"
                :style="{ width: getPrintImageWidth() + 'px', height: getPrintImageWidth() + 'px' }"
              />
            </div>

            <div class="qrcode-footer">
              <p class="device-type">设备类型: {{ getDeviceTypeName(deviceInfo.deviceType) }}</p>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="printPreviewVisible = false">取消</el-button>
          <el-button type="primary" @click="executePrint">
            <Icon icon="ep:printer" class="mr-5px" /> 确认打印
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { DeviceApi, QRCodeResponse } from '@/api/mqtt/device'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'

defineOptions({ name: 'QRCodeDialog' })

const dialogVisible = ref(false)
const printPreviewVisible = ref(false)
const loading = ref(false)
const qrcodeData = ref('')
const deviceInfo = ref<any>({})
const printContentRef = ref()
const qrcodeCardRef = ref()

// 二维码配置
const qrcodeConfig = reactive({
  size: 200
})

// 拖拽调整大小相关
const isResizing = ref(false)
const startX = ref(0)
const startSize = ref(0)

// 打印配置
const printConfig = reactive({
  size: 'medium',
  count: 1
})

// 获取设备类型名称
const getDeviceTypeName = (deviceType: number) => {
  const options = getIntDictOptions(DICT_TYPE.MQTT_DEVICE_TYPE)
  const option = options.find((item) => item.value === deviceType)
  return option ? option.label : '未知类型'
}

// 打开对话框
const open = async (device: any) => {
  deviceInfo.value = device
  dialogVisible.value = true
  await loadQRCode()
}

// 加载二维码
const loadQRCode = async () => {
  if (!deviceInfo.value.id) return

  loading.value = true
  try {
    const response = await DeviceApi.getDeviceQRCodeBase64(deviceInfo.value.id)
    // 后端返回的是 { deviceKey: "xxx", qrcode: "" }
    if (response && response.qrcode) {
      // 检查是否已经包含data URL前缀
      if (response.qrcode.startsWith('data:image/')) {
        qrcodeData.value = response.qrcode
      } else {
        qrcodeData.value = `data:image/png;base64,${response.qrcode}`
      }
    } else {
      throw new Error('二维码数据格式错误')
    }
  } catch (error) {
    console.error('加载二维码失败:', error)
    ElMessage.error('二维码加载失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  qrcodeData.value = ''
  deviceInfo.value = {}
}

// 重置大小
const resetSize = () => {
  qrcodeConfig.size = 200
}

// 开始拖拽调整大小
const startResize = (e: MouseEvent) => {
  e.preventDefault()
  isResizing.value = true
  startX.value = e.clientX
  startSize.value = qrcodeConfig.size

  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
}

// 处理拖拽调整大小
const handleResize = (e: MouseEvent) => {
  if (!isResizing.value) return

  const deltaX = e.clientX - startX.value
  const newSize = Math.max(100, Math.min(500, startSize.value + deltaX))
  qrcodeConfig.size = newSize
}

// 停止拖拽调整大小
const stopResize = () => {
  isResizing.value = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
}

// 获取打印项目宽度
const getPrintItemWidth = () => {
  const baseSize = qrcodeConfig.size
  switch (printConfig.size) {
    case 'small':
      return Math.max(150, baseSize * 0.8)
    case 'large':
      return Math.min(400, baseSize * 1.2)
    case 'current':
      return baseSize
    default:
      return baseSize
  }
}

// 获取打印图片宽度
const getPrintImageWidth = () => {
  const itemWidth = getPrintItemWidth()
  return itemWidth - 40 // 减去内边距
}

// 处理打印
const handlePrint = () => {
  printPreviewVisible.value = true
}

// 执行打印
const executePrint = () => {
  const printWindow = window.open('', '_blank')
  if (!printWindow) {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
    return
  }

  const printContent = printContentRef.value.innerHTML

  printWindow.document.write(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>设备二维码打印</title>
      <style>
        body { 
          margin: 0; 
          padding: 20px; 
          font-family: Arial, sans-serif; 
        }
        .print-item { 
          page-break-inside: avoid; 
          margin-bottom: 20px; 
          border: 1px solid #ddd; 
          padding: 15px; 
          text-align: center; 
          display: inline-block;
          vertical-align: top;
          margin-right: 20px;
        }
        .qrcode-header h3 { margin: 0 0 5px 0; font-size: 16px; }
        .device-id { margin: 5px 0; font-size: 12px; color: #666; }
        .qrcode-image img { max-width: 100%; height: auto; }
        .qrcode-footer p { margin: 3px 0; font-size: 12px; }
        .online { color: #27AA63; font-weight: bold; }
        .offline { color: #FF4949; font-weight: bold; }
        @media print {
          body { padding: 0; }
          .print-item { margin-bottom: 10px; page-break-inside: avoid; }
        }
      </style>
    </head>
    <body>
      ${printContent}
    </body>
    </html>
  `)

  printWindow.document.close()
  printWindow.focus()

  // 延迟打印，确保内容加载完成
  setTimeout(() => {
    printWindow.print()
    printWindow.close()
  }, 500)

  printPreviewVisible.value = false
  ElMessage.success('打印任务已发送')
}

// 暴露方法
defineExpose({
  open
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
})
</script>

<style scoped>
.qrcode-container {
  padding: 20px 0;
}

.size-control {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.size-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.size-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  min-width: 60px;
}

.qrcode-preview {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-container {
  width: 100%;
}

.qrcode-content {
  display: flex;
  justify-content: center;
}

.qrcode-card {
  background: white;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  position: relative;
  user-select: none;
}

.resize-handle {
  position: absolute;
  right: -8px;
  bottom: -8px;
  width: 16px;
  height: 16px;
  background: #409eff;
  border: 2px solid white;
  border-radius: 50%;
  cursor: se-resize;
  z-index: 10;
  transition: all 0.2s ease;
}

.resize-handle:hover {
  background: #66b1ff;
  transform: scale(1.1);
}

.resize-handle:active {
  background: #337ecc;
  transform: scale(0.95);
}

.qrcode-header h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
}

.device-id {
  margin: 5px 0;
  color: #666;
  font-size: 12px;
}

.qrcode-image {
  margin: 15px 0;
  display: flex;
  justify-content: center;
}

.qrcode-image img {
  border: 1px solid #ddd;
  border-radius: 4px;
}

.qrcode-footer p {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}

.online {
  color: #27aa63;
  font-weight: bold;
}

.offline {
  color: #ff4949;
  font-weight: bold;
}

.error-container {
  width: 100%;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.print-preview {
  max-height: 500px;
  overflow-y: auto;
}

.print-controls {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.print-info {
  margin-top: 10px;
  padding: 10px;
  background: #e1f3d8;
  border-radius: 4px;
  border-left: 4px solid #67c23a;
}

.print-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #606266;
}

.print-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.print-item {
  border: 1px solid #ddd;
  padding: 15px;
  text-align: center;
  background: white;
}

.print-item.small {
  width: 200px;
}

.print-item.medium {
  width: 300px;
}

.print-item.large {
  width: 400px;
}

.print-item .qrcode-image img {
  max-width: 100%;
  height: auto;
}
</style>
